package basic.study.leetcode;

/**
 * @ClassName Mid19
 * @Description 删除链表的倒数第N个节点
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/17 10:37
 * @Version 1.0
 */
public class Mid19 {
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast = head;
            ListNode slow = head;
            ListNode prev = null;
            //首先fast差n
            for (int i = 0; i < n; i++) {
                if (fast != null) {
                    fast = fast.next;
                } else {
                    return head;
                }
            }
            //然后一起
            while (fast != null) {
                fast = fast.next;
                prev = slow;
                slow = slow.next;
            }
            //删除
            if (prev == null) {
                head = head.next;
            } else {
                prev.next = prev.next.next;
            }

            //返回
            return head;
        }
    }

    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
}
